<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    // 订单状态
    const STATUS_PENDING = '未支付';
    const STATUS_PAID = '已支付';
    const STATUS_CANCELLED = '已取消';
    const STATUS_REFUNDED = '已退款';
    const STATUS_PROCESSING = '已处理';
    const STATUS_SHIPPED = '已发货';
    const STATUS_SIGNED = '已签收';
    const STATUS_RETURN_REQUEST = '申请退货';
    const STATUS_RETURN_SENT = '退货已发出';
    const STATUS_COMPLETED = '已完成';

    // 支付状态
    const PAYMENT_STATUS_PENDING = 'pending';
    const PAYMENT_STATUS_PAID = 'paid';
    const PAYMENT_STATUS_FAILED = 'failed';
    const PAYMENT_STATUS_REFUNDED = 'refunded';

    // 支付方法
    const PAYMENT_METHOD_WECHAT = 'wechat';
    const PAYMENT_METHOD_ALIPAY = 'alipay';

    protected $fillable = [
        'order_number',
        'wechat_service_account_user_id',
        'receiver_name',
        'receiver_phone',
        'shipping_address',
        'total_price',
        'status',
        'logistics_company',
        'tracking_number',
        'shipped_at',
        // 其他需要写入的字段
    ];

    protected $casts = [
        'subtotal' => 'float',
        'shipping_fee' => 'float',
        'discount' => 'float',
        'total' => 'float',
        'paid_at' => 'datetime',
        'shipped_at' => 'datetime',
        'completed_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    protected $appends = [
        'status_name',
        'payment_status_name'
    ];

    public function user()
    {
        return $this->belongsTo(WechatServiceAccountUser::class, 'wechat_service_account_user_id');
    }

    /**
     * 获取订单关联的商品
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function verificationCode()
    {
        return $this->belongsTo(VerificationCode::class, 'verification_code_id');
    }

    public function shippingAddress()
    {
        return $this->belongsTo(ShippingAddress::class);
    }

    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

    /**
     * 获取订单状态名称
     */
    public function getStatusNameAttribute()
    {
        $statuses = [
            self::STATUS_PENDING => '未支付',
            self::STATUS_PAID => '已支付',
            self::STATUS_CANCELLED => '已取消',
            self::STATUS_REFUNDED => '已退款',
            self::STATUS_PROCESSING => '已处理',
            self::STATUS_SHIPPED => '已发货',
            self::STATUS_SIGNED => '已签收',
            self::STATUS_RETURN_REQUEST => '申请退货',
            self::STATUS_RETURN_SENT => '退货已发出',
            self::STATUS_COMPLETED => '已完成'
        ];
        return $statuses[$this->status] ?? $this->status;
    }

    /**
     * 获取支付状态名称
     */
    public function getPaymentStatusNameAttribute()
    {
        $statuses = [
            self::PAYMENT_STATUS_PENDING => '待支付',
            self::PAYMENT_STATUS_PAID => '已支付',
            self::PAYMENT_STATUS_FAILED => '支付失败',
            self::PAYMENT_STATUS_REFUNDED => '已退款'
        ];
        return $statuses[$this->payment_status] ?? $this->payment_status;
    }

    /**
     * 生成订单号
     */
    public static function generateOrderNumber()
    {
        return date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

    /**
     * 计算订单总价
     */
    public function calculateTotal()
    {
        $this->subtotal = $this->items->sum(function ($item) {
            return $item->price * $item->quantity;
        });
        
        $this->total = $this->subtotal + $this->shipping_fee - $this->discount;
        return $this;
    }

    /**
     * 支付成功处理
     */
    public function markAsPaid($paymentMethod, $transactionId)
    {
        $this->update([
            'payment_method' => $paymentMethod,
            'payment_status' => self::PAYMENT_STATUS_PAID,
            'transaction_id' => $transactionId,
            'paid_at' => now(),
            'status' => self::STATUS_PAID
        ]);
    }

    /**
     * 取消订单处理
     */
    public function cancel()
    {
        if ($this->status !== self::STATUS_COMPLETED) {
            $this->update([
                'status' => self::STATUS_CANCELLED
            ]);
        }
    }
}